<?php
namespace Weixin\Controller;

use Think\Controller;
use Admin\Model\GoodsModel;
use Admin\Model\GoodsTypeModel;
use Admin\Model\AddressModel;
class IndexController extends Controller {
    
    private $http;
    private $weChat;
    private $goods;
    private $goodsType;
    private $address;
    function __construct() {
        parent::__construct();
        $this->goods = new GoodsModel();
        $this->goodsType = new GoodsTypeModel();
        $this->address = new AddressModel();
        $this->http = "http://tg.mdmtg.com.cn";
        
        vendor("Weixin.Wechat");
        $option["appid"] = C('wx_appid');
        $option["secret"] = C('wx_secret');
        $this->weChat = new \Wechat($option);
    }
    
    public function getToken(){
        //记录地推人员
        $working_id = I("working_id",1);
		//dump($working_id);die();
        session("working_id", $working_id);
        redirect($this->weChat->getOAuthRedirect($this->http.U('Weixin/Index/scGetToken')));
    }


    public function index(){
        if(I('code')){
            $wxUserInfo = $this->weChat->getOauthAccessToken();
            session("wxUserInfo",$wxUserInfo);
        }
        //$working_id = I("working_id",1);
        //session("working_id", $working_id);
        $data = $this->goodsType->getList([],true,true);
        $this->assign('data',$data);
        $this->display();
    }
    
    
    public function typelist(){
        $id = I('id');
        $where['id'] = $id;
        $data = $this->goodsType->getList($where,true,false);
        $this->assign('data',$data[0]);
        $this->display("goods_list");
    }
    
    public function searchGoods(){
        $keywords = I('keywords');
        $arr_keywords = explode(" ", $keywords);
        $where = [];
        if(count($arr_keywords) >= 1 ){
            foreach($arr_keywords as $v){
                $where['goods_tags'][] = ['like',"%$v%"];
                $where['goods_name'][] = ['like',"%$v%"];  
            }
            $where['goods_tags'][] = 'or';
            $where['goods_name'][] = 'or';
           $where['_logic'] = 'or'; 
        }
        
        //$where['goods_name'] = [['like','']];
        $data = $this->goods->getGoodsList($where,0,false);
        $this->assign("data",$data);
        
        $this->display("search_goods");
    }
    
    public function detail(){
        $id = I('id');
        $data = $this->goods->getGoodsInfoById($id);
        $this->assign("data",$data);
        $this->assign("goods_spec",json_encode($data['goods_spec']));
        $this->display("goods_detail");
    }

    
    public function settlement(){
        $id = I('id');
        $spec_id = I("spec_id");
        $data = $this->goods->getGoodsInfoById($id,$spec_id);
        $this->assign("data",$data);
        //dump($data);die();
        $address_id = I("address");
        if(!empty($address_id)){
			if($address_id == -1){
				$this->assign("noaddress",-1);
			}else{
				$addressInfo = $this->address->where("id=".$address_id)->find();
			}
            
        }else{
            $wxUserInfo = session("wxUserInfo");
            $openid = $wxUserInfo['openid'] ? $wxUserInfo['openid'] : "o4Utk09A3Q6h6i56AKgkPmpZaBAY";
            $addressInfo = $this->address->where("openid='".$openid."'")->find();
        }
        if(!empty($addressInfo)){
            $this->assign("addressInfo",$addressInfo);
        }
        $this->display();
    }
    
    public function address(){
        $wxUserInfo = session("wxUserInfo");
        $openid = $wxUserInfo['openid'];
        $this->assign("id",I('id'));
		$this->assign("goods_spec_id",I('goods_spec_id'));
        $this->assign("addressList",$this->address->getList(['openid'=>$openid]));
        $this->display();
    }
    
    public function address_new(){
        $this->assign("id",I('id'));
		$this->assign("goods_spec_id",I('goods_spec_id'));
        $this->display();
    }
    
    public function addAddress(){
        
    }
    
    public function doAddAddress(){
        $wxUserInfo = session("wxUserInfo");
        $openid = $wxUserInfo['openid'];
        $data = $this->address->create();
        $data['openid'] =  $openid;
        $this->address->add($data);
        $this->ajaxReturn(true);
    }
    
    public function delAddress(){
        $address_id = I("address_id");
        $this->address->where("id=".$address_id)->delete();
        $this->ajaxReturn(true);
    }
    
    public function wxNotify(){
        $callback = file_get_contents('php://input');
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($callback, 'SimpleXMLElement', LIBXML_NOCDATA)), true);        
        //file_put_contents("wx_callback.log", var_export($values,true),FILE_APPEND);   
        $out_trade_no = $values['out_trade_no'];
        if($values['result_code'] == 'SUCCESS' && $values['return_code'] == 'SUCCESS'){
            M('order')->where([
                'order_sn' => $out_trade_no
            ])->save(['status'=>2]);
        }
        echo 'success';
    }
    
    public function buildOrder(){
        $wxUserInfo = session("wxUserInfo");
        $pay_type = I("pay_type");
        $goods_id = I("goods_id");
        $spec_id = I("spec_id");
        $goodsInfo = $this->goods->getGoodsInfoById($goods_id,$spec_id);
		$cy_goods_type_list = C('CY_GOODS_TYPE');
		if($goodsInfo['stock'] <= 0){
			$this->ajaxReturn(false);
		}
		if(!empty($spec_id)){
			if($goodsInfo['goods_spec']['stock'] <= 0){
				$this->ajaxReturn(false);
			}
		}
        $saveData = [
            'working_id' => session('working_id'),
            'goods_id' => $goods_id,
            'goods_name' => $goodsInfo['goods_name'],
            'goods_data' => json_encode($goodsInfo),
            'price' => $goodsInfo['price'],
            'integral' => $goodsInfo['integral'],
            'num' => 1,
            'order_sn' => $goods_id."_".time(),
            'ctime' => time(),
            'pay_type' => $pay_type,
            'remark' => I('remark'),
            'status' => 1,
            'openid' => $wxUserInfo['openid'] ? $wxUserInfo['openid'] : "o4Utk09A3Q6h6i56AKgkPmpZaBAY" ,
            'clientIp' => get_client_ip(),
            'rpid' => Date("YmdHis").$goods_id,
			'cy_goods_type_1' => $goodsInfo['cy_goods_type_1'],
			'cy_goods_type_2' => $goodsInfo['cy_goods_type_2'],
			'cy_goods_type_1_name' => $cy_goods_type_list[$goodsInfo['cy_goods_type_1']]['name'],
			'cy_goods_type_2_name' => $cy_goods_type_list[$goodsInfo['cy_goods_type_1']]['sub_type'][$goodsInfo['cy_goods_type_2']]['name'],
			'cy_goods_type_rate' => $cy_goods_type_list[$goodsInfo['cy_goods_type_1']]['sub_type'][$goodsInfo['cy_goods_type_2']]['rate'],
			'goods_spec'=>$spec_id
        ];
        $order_id  = M('order')->add($saveData);
        //地址保存
		$addrss_id = I('address_id');
		if($addrss_id != -1){
			$addressInfo = $this->address->where("id=".$addrss_id)->find();
			$addData = [
				'order_id' => $order_id,
				'consignee' => $addressInfo['consignee'],
				'zip' => $addressInfo['zip'],
				'tel' => $addressInfo['tel'],
				'address' => $addressInfo['address'],
			];
			M("order_address")->add($addData);
			
		}
        
        
        //产品规格入库
        if(!empty($spec_id)){
            M('order_goods_spec')->add([
                'order_id' => $order_id,
                'spec_1' => $goodsInfo['goods_spec']['spec_1'],
                'spec_2' => $goodsInfo['goods_spec']['spec_2'],
                'goods_id' => $goodsInfo['goods_spec']['goods_id'],
                'spec_img' => $goodsInfo['goods_spec']['spec_img'],
                'ctime' => time(),
                'spec_price' => $goodsInfo['goods_spec']['spec_price'],
                'spec_integral' => $goodsInfo['goods_spec']['spec_integral'],
            ]);
        }
        if($pay_type == 1){
			//处理订单库存 商品总库存
            M('goods')->where(['id'=>$goods_id])->setDec('stock');
			//如果产品有规格  减少规格库存
			if(!empty($spec_id)){
				M('goods_spec')->where(['id'=>$goodsInfo['goods_spec']['id']])->setDec('stock');
			}
            $this->ajaxReturn(true);
        }
        //构造畅由积分够所需数据
        if($pay_type == 3){
            $requestData = [
                'funCode' => 'ORDER001',  // 功能代码
                'rpid'    => $saveData['rpid'],          // 跟踪号
                'reqDate' => Date('Ymd',$saveData['ctime']),          // 请求日期
                'reqTime' => Date('His',$saveData['ctime']),          // 请求时间
                'userId'  => '',          // 会员号   非必填
                'merId'   => C('CY_MERID'),          // 商户号 
                'clientIp'=> $saveData['clientIp'],          // 用户ip
                'orderId' => $saveData['order_sn'],          // 订单号
                'orderDate'=> Date('Ymd',$saveData['ctime']),         // 商户订单日期 
                'source'   => c('CY_SOURCE'),         // 来源/场景  ？？？？
                'orderDesc'=>'购买'.$saveData['goods_name']."畅由积分支付",          // 订单描述
                'payType'  => 'POINTS',         // 支付方式  POINTS 积分支付 CASH 现金支付  COMB 组合支付 CUST 自定义积分  和畅由人员沟通后确认
                'amount'   => (int)$saveData['integral'],         // 订单总金额  以分为单位  纯积分支付 amount = points  $saveData['price']*100
                'points'   => (int)$saveData['integral'],         // 积分值  以分为单位 payType为POINTS或COMB时有效  (int)$saveData['integral']
                'cash'     => 0,         // 现金金额  以分为单位 涉及到现金交易时有效
                'retUrl'   => C('CY_RETNOTIFY'),         // 前台返回地址  非必填 C('CY_RETNOTIFY')
                'notifyUrl'=> C('CY_NOTIFY'),         // 后台交易结果接收地址  非必填
                'effectSec'=> '3600',         // 订单有效时长
                'merPriv'  => '',         // 商户私有域
                'expand'   => '',
                
            ];
            $requestData['sign'] = $this->getCySign($requestData);
            file_put_contents("log.log", var_export($requestData,true),FILE_APPEND);
			//dump(C('ORDER001'));die();
            $d = $this->sendCyData(C('ORDER001'),json_encode($requestData));
            //请求畅游平台
            
            file_put_contents("log.log", var_export($d,TRUE),FILE_APPEND);
            if($d['retCode'] == '0000'){
                //处理form 表单所需字段
                $formData = [
                    'action' => C('CY_PAY00001'),
                    'data' => [
                        'funCode' => 'PAY00001',
                        'rpid'    => $requestData['rpid'],
                        'reqDate' => $requestData['reqDate'],
                        'reqTime' => $requestData['reqTime'],
                        'paySeq'  => $d['paySeq'],
                        'retUrl'  => C('CY_RETNOTIFY'),
                        'expand'  => ''
                    ]
                ];
                
                $formData['data']['sign'] = $this->getCySign($formData['data']);
                $formData['get_data'] = $formData['action']."&".http_build_query($formData['data']);
                $this->ajaxReturn($formData);
            }
            $this->ajaxReturn(false);
        }
        vendor("WeixinJSAPI.WxPay#Api");
        vendor("WeixinJSAPI.WxPay#JsApiPay");
        $tools = new \JsApiPay();
        $openId = $wxUserInfo['openid'];
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($goodsInfo['goods_name']);
        $input->SetAttach($goodsInfo['goods_name']);
        $input->SetOut_trade_no($saveData['order_sn']);
        $input->SetTotal_fee($saveData['price']*100);   //$saveData['price']*100
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($goodsInfo['goods_name']);
        $input->SetNotify_url("http://sc.mdmtg.com.cn".U('Weixin/Index/wxNotify'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->ajaxReturn($jsApiParameters);
    }
    
    private function getCySign($data){
        ksort($data);
        $data['key'] = C('CY_KEY');
        $string = $this->toUrlParams($data);
        return md5($string);
    }
    
    private  function toUrlParams($data){
        $buff = "";
        foreach ($data as $k => $v){
            if($k != "sign"  && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    
    private function sendCyData($url,$post){
        $aContext = array('http' => array('method' => 'POST',  
        'header'  => 'Content-type:application/json;charset=utf-8',  
        'content' => $post ));  
        $cxContext  = stream_context_create($aContext);  
        $d = file_get_contents($url,false,$cxContext); 
        return json_decode($d,true);
    }
    
    public function cyRetNotify(){
        $points = I("get.points");
        $this->assign("points",$points);
        $this->display();
    }
    
    public function cyNotify(){
        $callback = file_get_contents('php://input');
        file_put_contents("cy_callback.log", $callback,FILE_APPEND);   
        $callData = json_decode($callback,true);
        if($callData['transState'] == 2){
            //获取订单信息 和 通知返回信息 通知给面对面系统
            $orderInfo = M('order')->where(['order_sn' => $callData['orderId']])->find();
            $orderGoodsInfo = json_decode($orderInfo['goods_data'],true);
            $orderandcall = array_merge($orderInfo,$callData);
            $this->sendCyData(C('MDM_SAVEDATA'), json_encode($orderandcall));
            M('order')->where([
                'order_sn' => $callData['orderId']
            ])->save(['status'=>2]);
            $returnData = [
                'rpid' => $callData['rpid'],
                'retCode' => '0000',
                'retMsg' => '支付通知接受成功'
            ];
            $returnData['sign'] = $this->getCySign($returnData);
			//处理订单库存 商品总库存
            M('goods')->where(['id'=>$orderInfo['goods_id']])->setDec('stock');
			//如果产品有规格  减少规格库存
			if(!empty($orderInfo['goods_spec'])){
				M('goods_spec')->where(['id'=>$orderInfo['goods_spec']])->setDec('stock');
			}
			
            //处理畅由产品订单信息推送
            $sendProData = [
                'paySeq' => $callData['paySeq'],
                'merId' => $callData['merId'],
                'orderId'=>$callData['orderId'],
                'orderDate' => $callData['orderDate'],
                'amount' => (int)$callData['amount'],
                'affixation' => 0,
                'affixationRate' => 0,
                'exToken' => '',
                'clientIp' => $orderInfo['clientip'],
                'recName' => '',
                'recMobile' => '',
                'recAddress' => '',
                'shipType' =>'0',  //'short'
                'supplierOrderId' => $callData['orderId'],
                'channel' => 'web',
                'skus' => [
                    [
                        'subOrderId' => $callData['orderId'],
                        'goodsBrand' => $orderGoodsInfo['brand'],
                        'goodsType' => $orderInfo['cy_goods_type_2'],
                        'goodsName' => $orderInfo['goods_name'],
                        'goodsId'  => $orderInfo['goods_id'],
                        'goodsRate' => $orderInfo['cy_goods_type_rate']*100,
                        'goodsPrice' => (int)$callData['amount'],
                        'goodsNum' => 1,
                        'goodsTotalAmt' => (int)$callData['amount']
                    ]
                ]
            ];
            $sendProData['sign'] = $this->getCySign($sendProData);
            file_put_contents("CY_SEND_PRODATA.log",var_export($sendProData,true)."\n",FILE_APPEND);
            $send_prodata_res = $this->sendCyData(C('CY_SEND_PRODATA'), json_encode($sendProData));
			file_put_contents("CY_SEND_PRODATA.log","========================\n",FILE_APPEND);
            file_put_contents("CY_SEND_PRODATA.log",var_export($send_prodata_res,true)."\n",FILE_APPEND);
            ob_clean();
            echo http_build_query($returnData);
            die();
        }
    }
    
    public function refundOrder(){
        $callback = file_get_contents('php://input');
        file_put_contents("CY_REFUND_ORDER_NOTIFY.log", $callback."\n",FILE_APPEND); 
		$this->sendCyData(C('MDM_REFUNDDATA'),$callback);
		$callData = json_decode($callback,true);
		
		M('order')->where([
                'order_sn' => $callData['orderId']
            ])->save(['status'=>100]);
			
		$returnData = [
			'retCode' => '0000',
			'retMsg' => '退款通知接受成功'
		];
		$returnData['sign'] = $this->getCySign($returnData);	
		//echo http_build_query($returnData);
		echo json_encode($returnData);
		die();
    }
	
	public function sendPro(){
		$sendProData = array (
		  'paySeq' => '2018121063392015668871',
		  'merId' => 'W2000089',
		  'orderId' => '250_1544415897',
		  'orderDate' => '20181210',
		  'amount' => 1200,
		  'affixation' => 0,
		  'affixationRate' => 0,
		  'exToken' => '',
		  'clientIp' => '120.204.17.68',
		  'recName' => '',
		  'recMobile' => '',
		  'recAddress' => '',
		  'shipType' => '0',
		  'supplierOrderId' => '250_1544415897',
		  'channel' => 'web',
		  'skus' => 
		  array (
			0 => 
			array (
			  'subOrderId' => '250_1544415897',
			  'goodsBrand' => '耀泰',
			  'goodsType' => '000324',
			  'goodsName' => '蘑菇玻璃杯',
			  'goodsId' => '250',
			  'goodsRate' => 1600,
			  'goodsPrice' => 1200,
			  'goodsNum' => 1,
			  'goodsTotalAmt' => 1200,
			),
		  ),
		  'sign' => 'ebc7e4845496bfb9231721affb3f1590',
		);
            //$sendProData['sign'] = $this->getCySign($sendProData);
            //file_put_contents("CY_SEND_PRODATA.log",var_export($sendProData,true)."\n",FILE_APPEND);
            $send_prodata_res = $this->sendCyData(C('CY_SEND_PRODATA'), json_encode($sendProData));
			//file_put_contents("CY_SEND_PRODATA.log","========================\n",FILE_APPEND);
            //file_put_contents("CY_SEND_PRODATA.log",var_export($send_prodata_res,true)."\n",FILE_APPEND);
            //ob_clean();
            dump($send_prodata_res);
            die();
	}
}